<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, watch } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import { LawsuitDefenseApi, LawsuitDefenseVO } from '@/api/legal/GroupCaseApproval/lawsuitdefense'
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'
import { getFileName, parseArrayField, buildFileList } from '@/utils/fileUtils'


const headerObj = ref({ Authorization: 'Bearer ' + getAccessToken() })
const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)  //页面详情id
const resubmit = ref(0)



// 指定审批人
const processDefineKey = 'Law_LawsuitDefense' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	eids: []
})
const formData = ref<LawsuitDefenseVO>({
	id: undefined,
	reportingUnit: undefined,
	applicationDate: undefined,
	name: undefined,
	gender: undefined,
	age: undefined,
	ethnicity: undefined,
	education: undefined,
	position: undefined,
	title: undefined,
} as any)

let formFields = [

	{ type: 'input', prop: 'defendant', label: '涉案单位', placeholder: '请输入涉案单位' },
	{ type: 'input', prop: 'submitter', label: '资料提交人', placeholder: '请输入资料提交人' },
	{ type: 'input', prop: 'submitterContact', label: '联系电话', placeholder: '请输入联系电话' },
	{ type: 'textarea', prop: 'caseReason', label: '案由', placeholder: '请输入案由' },
	{ type: 'input', prop: 'caseTarget', label: '涉案标的', placeholder: '请输入涉案标的', inputType: 'number' },
	{ type: 'input', prop: 'claimant', label: '起诉人', placeholder: '请输入起诉人' },
	{ type: 'input', prop: 'claimantContact', label: '起诉人联系电话', placeholder: '请输入起诉人联系电话' },
	{ type: 'datetime', prop: 'submitDate', label: '提交时间', placeholder: '选择提交时间', datetimeType: 'date' },
	{ type: 'input', prop: 'submitCount', label: '提交份数', placeholder: '请输入提交份数' },
	{ type: 'textarea', prop: 'caseSummary', label: '简要案情', placeholder: '请输入简要案情' },
	{ type: 'textarea', prop: 'lawsuitReason', label: '被起诉理由', placeholder: '请输入被起诉理由' },
	{ type: 'textarea', prop: 'remark', label: '备注', placeholder: '请输入备注' },
	{
		type: 'upload', prop: 'eids', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		// limit: 1,
		accept: 'all',
		isMultipleArray: true,
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'eids',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},
] as any
const formRules = reactive({
	defendant: [
		{
			required: true,
			message: '涉案单位',
			trigger: ['blur', 'change'],
		},
	],
	submitter: [
		{
			required: true,
			message: '资料提交人',
			trigger: ['blur', 'change'],
		},
	],
	submitterContact: [
		{
			required: true,
			message: '联系电话',
			trigger: ['blur', 'change'],
		},
		{
			pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
			,
			message: '请输入有效的电话号',
			trigger: ['blur', 'change'],
		}
	]
})

onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{
					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						if (value && Array.isArray(value) && value.length > 0) {
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await LawsuitDefenseApi.getLawsuitDefense(Number(detailId.value))
		formData.value = data
		if (formData.value.submitDate) {
			formData.value.submitDate = parseDateToTimestamp(formData.value.submitDate)
		}
		// 附件字段回显
		formData.value.eids = parseArrayField(data.eids);
		formData.value.ename = parseArrayField(data.ename);
		fileLists.value.eids = buildFileList(formData.value.eids, formData.value.ename) as any;
	} catch (error) {
		console.log('加载数据失败')
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	try {
		if (type === 'update') {
			await LawsuitDefenseApi.updateLawsuitDefense(data)
			toast.success('编辑成功');
		} else {
			await LawsuitDefenseApi.createLawsuitDefense(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/Legal/GroupCaseApproval/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/Legal/GroupCaseApproval/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>